package cn.clx.ymcc.rocketmq;

import cn.clx.ymcc.domain.PayOrder;
import cn.clx.ymcc.service.IPayOrderService;
import cn.clx.ymcc.util.AssertUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;

/**
 *  pay支付，mq发送延迟消息，超时这里消费消息---取消订单，让支付宝关闭此订单的接口
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "pay-timeout-topic",
        selectorExpression="pay-timeout-tags"	//tags
                ,consumerGroup = "service-order-to-pay-paytimeout-consumer",
        messageModel = MessageModel.BROADCASTING)
public class OrderToPayTimeOutConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;


    /**
     * 订单超时未支付，设置支付状态
     * 消费消息报错，意味着消费失败，从新就如队列进行消费，直到mq自动清除 ，或者消费成功为止
     * @param message
     */
    @Override
    @Transactional
    public void onMessage(MessageExt message) {
        log.info("pay微服务延迟消息消费");
        byte[] body = message.getBody();
        if(body==null){
            return;
        }
        String ordersn = new String(body, StandardCharsets.UTF_8);
        PayOrder payOrder = payOrderService.checkPayOrder(ordersn);
        AssertUtil.isNotNull(payOrder,"课程订单异常");
        boolean paystatus = payOrder.getPayStatus().intValue() == PayOrder.STATE_WAIT_PAY;
        if(paystatus){
            payOrder.setPayStatus(PayOrder.STATE_CANCEL);//修改支付单的状态为 支付取消
            payOrderService.updateById(payOrder);
            //调用支付宝，关闭支付
            try {
                AlipayTradeCloseResponse close = Factory.Payment.Common().close(ordersn);
            } catch (Exception e) {
                e.printStackTrace();
                /**
                 * 做兜底
                 * 1.重试3次
                 * 2.保存要取消支付单的记录到数据库，运维人员来人工跟进
                 * 3.给运维人员发站内信，邮件，消息---- 对接钉钉推销
                 */
            }

        }

    }
}